package com.firstclass.utils;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * token工具类
 */
public class TokenUtils {
    private final static String TOKEN_HEADER = "token";

    /**
     * 从请求头部中获取token
     *
     * @param request request对象
     * @return token字符串
     */
    public static String getToken(HttpServletRequest request) {
        return request.getHeader(TOKEN_HEADER);
    }

    /**
     * 生成 token
     *
     * @param id
     * @return
     */
    public static String generateToken(String id) {
        String signature = DigestUtils.md5DigestAsHex(id.getBytes());
        return Base64.getEncoder().encodeToString(id.getBytes()) + "." + Base64.getEncoder().encodeToString(signature.getBytes());
    }

    /**
     * 解析 token
     *
     * @param token
     * @return
     */
    public static String parseToken(String token) {
        String[] tokens = token.split("\\.");
        if (tokens.length != 2) {
            return null;
        }
        String payload = tokens[0];
        String signature = tokens[1];
        String payloadBase64 = new String(Base64.getDecoder().decode(payload));
        String signatureBase64 = new String(Base64.getDecoder().decode(signature));
        if (!signatureBase64.equals(DigestUtils.md5DigestAsHex(payloadBase64.getBytes()))) {
            return null;
        }
        return FastJsonUtils.parseObject(payloadBase64, String.class);
    }

}
